<?php
namespace Admin\Controller;

use Think\Controller;

class OrderController extends Controller
{

    public function queryOrder()
    {
        //收入开始
        $order_item = M('order_item');
        $totalPrice = $order_item->query("SELECT  sum(price) AS prices FROM wm_order WHERE order_status =1");
        $orderNum = $order_item->query("SELECT  count(1) AS orderNum FROM  wm_order");
        $todaytotalPrice = $order_item->query("SELECT  sum(price) AS prices FROM wm_order WHERE order_status =1 AND to_days(create_time) = to_days(now())");
        $todayorderNum = $order_item->query("SELECT  count(1) AS orderNum FROM  wm_order WHERE to_days(create_time) = to_days(now())");
        //收入结束
        //前台赋值
        $this->assign('totalPrice', ($totalPrice[0]["prices"]));
        $this->assign('orderNum', ($orderNum[0]["ordernum"]));
        $this->assign('todaytotalPrice', ($todaytotalPrice[0]["prices"]));
        $this->assign('todayorderNum', ($todayorderNum[0]["ordernum"]));
        $this->display();
    }

    /* public function incomeCount(){
         $this->display();
     }
 */
    public function incomeAndCountQuery()
    {
        $beginTime = I('beginTime');
        $endTime = I('endTime');
        $order_item = M('order_item');
        $totalPrice = null;
        $orderNum = null;
        if ($beginTime == $endTime) {
            $totalPrice = $order_item->query("SELECT  sum(price) AS prices FROM wm_order WHERE order_status =1 AND to_days(create_time) = to_days('" . $beginTime . "')");
            $orderNum = $order_item->query("SELECT  count(1) AS orderNum FROM  wm_order WHERE  to_days(create_time) = to_days('" . $beginTime . "')");
//                    select * from wm_order where to_days(create_time) = to_days("2017-10-27");
        }
        if ($beginTime != $endTime) {
            $totalPrice = $order_item->query("SELECT  sum(price) AS prices FROM wm_order WHERE order_status =1 AND create_time between '" . $beginTime . "' and '" . $endTime . "'");
            $orderNum = $order_item->query("SELECT  count(1) AS orderNum FROM  wm_order WHERE create_time between '" . $beginTime . "' and '" . $endTime . "'");
//            $wheresql=$wheresql."WHERE create_time between '".$beginTime."' and '".$endTime."' and";
        }
//        $totalPrice=$order_item->query("SELECT  sum(price) AS prices FROM wm_order WHERE order_status =1");
//        $orderNum=$order_item->query("SELECT  count(1) AS orderNum FROM  wm_order");

        /*  $responce=array();
          array_push($responce, $totalPrice[0]["prices"]);
          array_push($responce, $orderNum[0]["ordernum"]);*/
        $responce[totalPrice] = $totalPrice[0]["prices"];//总记录数
        $responce[orderNum] = $orderNum[0]["ordernum"];
        echo json_encode($responce); //输出JSON数据
    }


    public function menuCount()
    {
        $order = M('order_item');
        $result = $order->query("SELECT  item_name,  count(1) AS counts  FROM  wm_order_item  GROUP BY  item_name");
        $totalPrice = $order->query("SELECT  sum(price) AS prices FROM wm_order WHERE order_status =1");
        $orderNum = $order->query("SELECT  count(1) AS orderNum FROM  wm_order");

        $todaytotalPrice = $order->query("SELECT  sum(price) AS prices FROM wm_order WHERE order_status =1 AND to_days(create_time) = to_days(now())");
        $todayorderNum = $order->query("SELECT  count(1) AS orderNum FROM  wm_order WHERE to_days(create_time) = to_days(now())");

        $responce = array();
        $itemName = array();
        $itemNameCount = array();
        /* for ($i= 0;$i< count($result); $i++){
             array_push($itemName,$result[i]['item_name']);
             array_push($itemNameCount,$result[i]['counts']);
         }*/
        foreach ($result as $value) {
            array_push($itemName, $value['item_name']);
            array_push($itemNameCount, $value['counts']);
        }
//        echo ($orderNum[0]["orderNum"]);
//        var_dump($orderNum);
        $responce['itemNameResult'] = $itemName;
        $responce['itemNameCountResult'] = $itemNameCount;
        $this->assign('itemName', json_encode($itemName));
        $this->assign('itemNameCount', json_encode($itemNameCount));
        $this->assign('totalPrice', ($totalPrice[0]["prices"]));
        $this->assign('orderNum', ($orderNum[0]["ordernum"]));

        $this->assign('todaytotalPrice', ($todaytotalPrice[0]["prices"]));
        $this->assign('todayorderNum', ($todayorderNum[0]["ordernum"]));
//        echo json_encode($itemName); //输出JSON数据

        $this->display();
    }


    public function showjqgriddata()
    {
        $order = M('order');
        $beginTime = I('beginTime');
        $endTime = I('endTime');
        $orderId = I('orderId');
        $userName = I('userName');
        $tableNum = I('tableNum');


//        $map=array();
        $wheresql = "from wm_order ";
        if ($beginTime != null || $endTime != null || $orderId != null || $userName != null || $tableNum != null) {

            if ($beginTime != null && $endTime != null) {
//                $map['create_time'] = array(array('EGT', $beginTime), array('ELT', $endTime));BETWEEN '2010-08-01' AND '2010-08-19'
                if ($beginTime == $endTime) {
                    $wheresql = $wheresql . "WHERE to_days(create_time) = to_days('" . $beginTime . "') and";
//                    select * from wm_order where to_days(create_time) = to_days("2017-10-27");
                } else {
                    $wheresql = $wheresql . "WHERE create_time between '" . $beginTime . "' and '" . $endTime . "' and";
                }

            }
            if ($orderId != null) {
//                $map['order_id'] =$orderId;
                $wheresql = $wheresql . " order_id = '" . $orderId . "' and";
            }
            if ($userName != null) {
//                $map['user_name'] =$userName;
                $wheresql = $wheresql . " user_name = '" . $userName . "' and";
            }
            if ($tableNum != null) {
//                $map['table_num'] =$tableNum;
                $wheresql = $wheresql . " table_num = '" . $tableNum . "'";
            }
        }
        if (substr($wheresql, strlen($wheresql) - 3, 3) == 'and') {
            $wheresql = substr($wheresql, 0, -3);
        }
//        $wheresql=$wheresql." ORDER BY create_time DESC";
        $page = $_GET['page']; //获取请求的页数
        $rows = $_GET['rows']; //获取每页显示记录数
//        $count =$order->where($map)->count();
//        echo $wheresql;
        $count = M('order')->query("select count(*) " . $wheresql)[0]["count(*)"];
//        echo $count[0]["count(*)"];
//        var_dump($count);

        if ($page == null) {
            $page = 1;
        }
        $offset = $rows * ($page - 1);//计算记录偏移量
        /*  $result= M('order')->where($map)
              ->limit($offset . ',' . $rows)
              ->select();*/
        $wheresql = "select * " . $wheresql . "ORDER BY create_time DESC limit " . $offset . "," . $rows . "";
        $result = M('order')->query($wheresql);

        if ($count % $rows == 0) {
            $total = $count / $rows;
        }
        if ($count % $rows != 0) {
            $total = floor($count / $rows) + 1;

        }


        $responce['page'] = $page;
        $responce['total'] = $total;//总页数
        $responce['records'] = $count;//总记录数
        $responce['rows'] = $result;
        echo json_encode($responce); //输出JSON数据

    }


    public function checkout()
    {
        $tableNum = I('tableNum');
        $table_num = $tableNum;
        $orderId = I('orderId');
        if (strstr($tableNum, ',')) {
            $tableNum = explode(',', $tableNum);
        }
        $data['table_num'] = $table_num;
        $data['order_id'] = $orderId;
        $order = M('order');
        $data2['status'] = 1;
        $data2['tableNum'] = $tableNum;
        $data1['order_status'] = 1;
        if ($order->where($data)->save($data1)) {
            $table = M('table');
            $tableInfo['table_status'] = 0;
            if (strstr($table_num, ',')) {
                foreach ($tableNum as $table_info) {
                    $table->where('table_num=' . $table_info)->save($tableInfo);
                }
            } else {
                $table->where('table_num=' . $table_num)->save($tableInfo);
            }
            $data['status'] = 0;
            show(30001, "确认订单成功：第" . $table_num . "桌订单完成", $data2);
        } else {
            show(31001, "确认订单失败：第" . $table_num . "桌空闲", $data2);
        }
        show(32001, "请求失败");

    }


    public function addOrder()
    {
        $tableNum = I('tableNum');
        $table_num = $tableNum;
        if (is_array($tableNum)) {
            $tableNum = implode(',', $tableNum);
        }

        $table = M('table');
        $tableInfo['table_status'] = 1;
        if (is_array($table_num)) {
            $sql = "UPDATE wm_table SET table_status=1  WHERE  table_num in(" . $tableNum . ") AND  table_status=0";
            $a = array();
            foreach ($table_num as $table_info) {
                $where['table_num'] = $table_info;

                $result = $table->where($where)->find();
                if ($result) {
                    if ($result['table_status'] == 1) {
                        array_push($a, $table_info);
                    }
                }

            }
            if (count($a) >=1) {
                show(33001, "您选择的桌号" . implode(',', $a) . "已经被占用，请重新选择");
            }
            if (!$table->execute($sql)) {
                show(33001, "您选择的桌号".$a."已经被占用，请重新选择");
            }
            /*if (!$table->execute($sql)){
                show(33001, '您选择的桌号已经被占用，请重新选择');
            }*/


        } else {
            $where['table_status'] = 0;
            $where['table_num'] = $tableNum;
            if ($table->find($table_num)['table_status']==1 || !$table->where($where)->save($tableInfo)) {
                show(33001, "您选择的桌号".$tableNum."已经被占用，请重新选择");
            }
        }

        $userName = $_POST['userName'];
        $userContact = $_POST['userContact'];
        $danhao = date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
        $dishs = $_POST['dishs'];
//        var_dump($dishs);
//        $jsonArr = json_decode($dishs, TRUE);
        $order_item = M("order_item"); // 实例化order对象
        $totalprice=0;
        $item_count=0;

//        echo count($dishs);
        for ($i= 0;$i< count($dishs); $i++){
            $data['order_id']=$danhao;
            $data['item_id']=$dishs[$i]['itemId'];
            $data['item_name']=$dishs[$i]['name'];
            $data['item_price']=$dishs[$i]['price'];
            $data['item_count']=$dishs[$i]['count'];
            $data['create_time'] = date("Y-m-d H:i:s");// 当前时间年月日 时分秒;
            $data['update_time'] = date("Y-m-d H:i:s");// 当前时间年月日 时分秒;
            $totalprice+=$dishs[$i]['price']*$dishs[$i]['count'];
            $item_count+=$dishs[$i]['count'];
            if (!$order_item->add($data)){
                show(33002, "提交订单失败");

            };
        }

        $order = M("Order"); // 实例化order对象
        $data['order_id']=$danhao;
        $data['table_num'] = $tableNum;
        $data['user_name'] = $userName;
        $data['user_contact'] = $userContact;
        $data['price'] = $totalprice;
        $data['item_count'] = $item_count;
        $data['order_status'] = 1;
        $data['order_status'] = 0;

        $data['create_time'] = date("Y-m-d H:i:s");// 当前时间年月日 时分秒;
        $data['update_time'] = date("Y-m-d H:i:s");// 当前时间年月日 时分秒;
        if (!$order->add($data)){
            show(33002, "提交订单失败");

        }

        $result['orderId']=$danhao;
        $result['code']=22001;
        show(22001, '提交订单成功', $danhao);
    }

    /*
         $table = M('table');
   if ($table->find($tableNum)['table_status']!=0){
      $data['tableNum']=1;
      $data['status']=0;
      show(31001, '确认订单失败：第'.$tableNum.'桌空闲',$data);
  }
 if($order->add($data)){
     $data['tableNum']=1;
     $data['status']=0;
     show(31001, '确认订单失败：第'.$tableNum.'桌空闲',$data);

 } ;
  $data['tableNum']=1;
  $data['status']=0;
  show(30001, '确认订单成功：第1桌订单完成',$data);
 /* $result["orderId"]=$danhao;
  $result["status"]=22001;
//        var_dump($result);
  echo json_encode($result);*/


    public function getOrderList()
    {
        $order = M('order')->query('SELECT * from wm_order ORDER BY create_time DESC');
        $order = M('order')->query('SELECT * from wm_order WHERE order_status = 0 ORDER BY create_time DESC;');
        $a = array();
        for ($i = 0; $i < count($order); $i++) {
            $data['tableNum'] = $order[$i]['table_num'];
            $data['orderId'] = $order[$i]['order_id'];
            $data['name'] = "桌号" . $order[$i]['table_num'];
            $data['count'] = $order[$i]['item_count'];
            $data['price'] = $order[$i]['price'];
            $data['orderStatus'] = $order[$i]['order_status'];
            $data['create_time'] = $order[$i]['create_time'];


            $order_item = M('order_item')->where('order_id=' . $order[$i]['order_id'])->select();
            $dishs = M('dish')->select();
            $b = array();
            foreach ($order_item as $dishInfo) {
                $dish = new \stdClass();
                $dish->itemId = $dishInfo['item_id'];
                $dish->name = $dishInfo['item_name'];
                $dish->count = $dishInfo['item_count'];
                $dish->price = $dishInfo['item_price'];
                array_push($b, $dish);
            }

            $data['dish'] = $b;
            array_push($a, $data);
        }
        echo json_encode($a);
    }
}